package com.fs.luban.security.model;

import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import com.fs.luban.common.Constant;
import com.fs.luban.module.sys.entity.vo.SysResourceVO;
import com.google.common.collect.Lists;

import lombok.Data;

/**
 * 鲁班用户认证 model
 */
@Data
public class LubanUserDetails implements UserDetails {

	private static final long serialVersionUID = 1L;

	/**
	 * id
	 */
	private Integer id;
	/**
	 * 部门id
	 */
	private Integer orgId;
	/**
	 * 部门名称
	 */
	private String orgName;
	/**
	 * 角色id
	 */
	private Integer roleId;
	/**
	 * 角色名称
	 */
	private String roleName;
	/**
	 * 账号
	 */
	private String username;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 姓名
	 */
	private String name;
	/**
	 * 性别{0:未知,1:男,2:女}
	 */
	private Integer sex;
	/**
	 * 电话
	 */
	private String mobile;
	/**
	 * 邮箱
	 */
	private String email;
	/**
	 * 头像
	 */
	private String avator;
	/**
	 * 状态{0:停用,1:正常,2:锁定}
	 */
	private Integer status;

	/**
	 * 可访问资源
	 */
	private List<SysResourceVO> resList;

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> authorityList = Lists.newArrayList();
		if (!CollectionUtils.isEmpty(resList)) {
			for (SysResourceVO resVO : resList) {
				authorityList.addAll(getAllAuthorities(resVO));
			}
		}
		return authorityList;
	}

	// 递归获取所有资源信息
	private List<GrantedAuthority> getAllAuthorities(SysResourceVO resVO) {
		List<GrantedAuthority> authorityList = Lists.newArrayList();
		if (null != resVO) {
			authorityList.add(new LubanGrantedAuthority(resVO.getPermission(), resVO.getUrl(), Constant.SysResource.Methed.getNameByCode(resVO.getMethod())));
			if (!CollectionUtils.isEmpty(resVO.getChildren())) {
				for (SysResourceVO children : resVO.getChildren()) {
					authorityList.addAll(getAllAuthorities(children));
				}
			}
		}
		return authorityList;
	}

	@Override
	public String getPassword() {
		return this.password;
	}

	@Override
	public String getUsername() {
		return this.username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return !(Constant.SysUser.States.Locked.getStatus() == this.status);
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return Constant.SysUser.States.Enable.getStatus() == this.status;
	}

}
